
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_wan_android/bean/project_list_bean.dart';
import 'package:flutter_wan_android/blocs/base/bloc_provider.dart';
import 'package:flutter_wan_android/blocs/project_bloc.dart';
import 'package:flutter_wan_android/res/colors.dart';
import 'package:flutter_wan_android/widgets/empty_widget.dart';
import 'package:flutter_wan_android/widgets/home_widgets.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class ProjectListPage extends StatefulWidget{

  final int cid;

  const ProjectListPage({Key key, this.cid}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return _ProjectListState(cid);
  }


}


class _ProjectListState extends State<ProjectListPage>{


  ProjectBloc _bloc;
  final int cid;

  _ProjectListState(this.cid);


  @override
  void initState() {
    super.initState();
    _bloc= BlocProvider.of<ProjectBloc>(context);
    _bloc.getProjectList(_pageIndex, cid);
  }

  @override
  Widget build(BuildContext context) {
    return _streamBuilder(context, cid);
  }


  StreamBuilder _streamBuilder(BuildContext context, int id,){
    return StreamBuilder<List<ProjectItem>>(
        stream: _bloc.listStream,
        builder: (context,AsyncSnapshot<List<ProjectItem>> snapshot){
          if(_pageIndex==1){
            _refreshController.refreshCompleted();
          }else{
            _refreshController.loadComplete();
          }

          if(_bloc.listData.length==0 && _pageIndex==1){
            return LoadingView();
          }
          return SmartRefresher(
            controller: _refreshController,
            child: ListView.separated(itemBuilder: (context,index){
              return ProjectItemView(_bloc.listData.elementAt(index));
            }, separatorBuilder: (context, index) {
              return Container(
                height: 0.5,
                color: Colors.transparent,
              );
            }, itemCount: _bloc.listData.length),
            enablePullUp: true,
            footer: ClassicFooter(
              loadStyle: LoadStyle.ShowAlways,
              completeDuration: Duration(milliseconds: 500),

            ),
            header:WaterDropMaterialHeader(
              backgroundColor: XColors.refreshStyleColor,
            ),
            onRefresh: () async{
              _refresh(id);
            },
            onLoading: ()async{
              _loading(id);
            },
          );
        }
    );
  }




  void _loading(cid) {
    ++_pageIndex;
    _bloc.getProjectList(_pageIndex,cid);
  }

  void _refresh(cid) {
    _pageIndex = 1;
    _bloc.getProjectList(_pageIndex,cid);
  }


  int _pageIndex = 1;
  RefreshController _refreshController = RefreshController(initialRefresh: false);

}